package cn.dakaqi.services.user.impl;

import cn.dakaqi.dao.user.AccountDao;
import cn.dakaqi.dao.user.UserOpenIdDao;
import cn.dakaqi.entities.Group;
import cn.dakaqi.entities.GroupVolunteer;
import cn.dakaqi.entities.user.User;
import cn.dakaqi.entities.user.UserOpenId;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.enumerate.CommonStatusCode;
import cn.dakaqi.qnzyz.BHMemberService;
import cn.dakaqi.services.GroupService;
import cn.dakaqi.services.GroupVolunteerService;
import cn.dakaqi.services.LogService;
import cn.dakaqi.services.user.UserService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.MD5Util;
import cn.dakaqi.utils.UUIDHexGenerator;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import cn.dakaqi.utils.sms.rongcloud.RongCloudSMS;
import cn.dakaqi.vo.response.UserVolunteer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.utils.Clock;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author chunyang on 2016/4/7.
 */
@Component(value = "userService")
@Transactional
public class UserServiceImpl implements UserService
{
    @Autowired
    AccountDao accountDao;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupService groupService;
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    private RedisClientTemplate redisClientTemplate;
    @Autowired
    private UserOpenIdDao userOpenIdDao;
    @Autowired
    private BHMemberService bhMemberService;
    @Autowired
    private LogService logService;

    private Clock clock = Clock.DEFAULT;

    @Override
    public User findOne(Long userId) throws ServiceRuntimeException
    {
        return accountDao.findOne(userId);
    }

    public List<User> getAllUser()
    {
        return (List<User>) accountDao.findAll();
    }

    public User getUser(Long id)
    {
        return accountDao.findOne(id);
    }

    public User findByMobile(String mobile)
    {
        return accountDao.findByMobile(mobile);
    }

    @Override
    public User findByEmail(String email) throws ServiceRuntimeException
    {
        return accountDao.findByEmail(email);
    }

    @Override
    public User findByMobileOrEmail(String mobile, String email)
    {
        return accountDao.findByMobileOrEmail(mobile, email);
    }

    @Override
    public User login(String mobile, String password) throws ServiceRuntimeException
    {
        User user = null;
        if (mobile.contains("@"))
        {
            user = findByEmail(mobile);
        } else
            user = findByMobile(mobile);
        if (null == user)
            return null;

        String temp = MD5Util.MD5(password);
        if (user.getPassword().toLowerCase().equals(temp.toLowerCase()))
            return user;
        else
            return null;
    }

    @Override
    public User login(String mobile, String password, String area, double lng, double lat) throws ServiceRuntimeException
    {
        User user = null;
        if (mobile.contains("@"))
        {
            user = findByEmail(mobile);
        } else
        {
            user = findByMobile(mobile);
        }

        if (null == user)
        {
            logService.save(100, "用户【" + mobile + "】从" + area + "," + lng + "," + lat + ",登录失败");
            return null;
        }

        String temp = MD5Util.MD5(password);
        if (user.getPassword().toLowerCase().equals(temp.toLowerCase()))
        {
            logService.save(100, "用户【" + mobile + "】从" + area + "," + lng + "," + lat + ",成功登录");
            return user;
        } else
            return null;
    }

    @Override
    public UserVolunteer saveUser(User user, String code) throws ServiceRuntimeException
    {
        if (!checkVerifierCode(user.getMobile(), code))
        {
            throw new ServiceRuntimeException(CommonStatusCode.COMMON_VERIFIER_CODE_ERROR.getStatusCode(),
                    CommonStatusCode.COMMON_VERIFIER_CODE_ERROR.getStatusMessage());
        }

        //检查当前用户是否已存在
        User user1 = this.findByMobileOrEmail(user.getMobile(), user.getMobile());
        if (null != user1)
        {
            throw new ServiceRuntimeException(CommonStatusCode.USER_EXISTS.getStatusCode(),
                    CommonStatusCode.USER_EXISTS.getStatusMessage());
        }

        try
        {
            reg2BHPlatforpUser(user);
        } catch (Exception e)
        {
            e.printStackTrace();
            try
            {
                throw e;
            } catch (Exception e1)
            {
                e1.printStackTrace();
            }
        }

        user.setPassword(MD5Util.MD5(user.getPassword()));
        user.setRoles("user");
        user.setCreateTime(clock.getCurrentDate());
        accountDao.save(user);

        //保存志愿者信息
        Volunteer volunteer = new Volunteer();
        volunteer.setMemberCode(UUIDHexGenerator.generator());
        volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        volunteer.setMobile(user.getMobile());
        volunteer.setNickName(user.getNickName());
        volunteer.setRealName(user.getRealName());
        volunteer.setUserId(user.getId());
        volunteer.setTimes(0L);
        volunteer.setHeadUrl(DKQConstant.HEAR_URL);
        volunteer.setSex("男");
        volunteer.setClient(user.getClient());
        this.volunteerService.saveVolunteer(volunteer);
        clearVeriferCode(user.getMobile());

        //UserVolunteer
        UserVolunteer userVolunteer = new UserVolunteer();
        userVolunteer.setUser(user);
        userVolunteer.setVolunteer(volunteer);
        return userVolunteer;

    }

    @Override
    public User saveUserOnly(User user, String code) throws ServiceRuntimeException
    {
        if (!checkVerifierCode(user.getMobile(), code))
        {
            throw new ServiceRuntimeException(CommonStatusCode.COMMON_VERIFIER_CODE_ERROR.getStatusCode(),
                    CommonStatusCode.COMMON_VERIFIER_CODE_ERROR.getStatusMessage());
        }

        //检查当前用户是否已存在
        User user1 = this.findByMobileOrEmail(user.getMobile(), (user.getMobile()));
        if (null != user1)
        {
            throw new ServiceRuntimeException(CommonStatusCode.USER_EXISTS.getStatusCode(),
                    CommonStatusCode.USER_EXISTS.getStatusMessage());
        }

        try
        {
            reg2BHPlatforpUser(user);
        } catch (Exception e)
        {
            e.printStackTrace();
            try
            {
                throw e;
            } catch (Exception e1)
            {
                e1.printStackTrace();
            }
        }

        user.setPassword(MD5Util.MD5(user.getPassword()));
        user.setRoles("user");
        user.setCreateTime(clock.getCurrentDate());
        accountDao.save(user);

        return user;
    }

    private void reg2BHPlatforpUser(User user) throws Exception
    {
        if (null != user.getMobile() && StringUtils.isNotBlank(user.getMobile()))
            bhMemberService.reg4Platform(user.getMobile(), user.getPassword());
    }

    @Override
    public void saveThirdPartyUser(User user, Volunteer volunteer) throws ServiceRuntimeException
    {
        try
        {
            reg2BHPlatforpUser(user);
        } catch (Exception e)
        {
            e.printStackTrace();
            try
            {
                throw e;
            } catch (Exception e1)
            {
                e1.printStackTrace();
            }
        }

        //检查当前用户是否已存在
        user.setPassword(MD5Util.MD5("123456"));
        user.setRoles("user");
        user.setCreateTime(clock.getCurrentDate());
        Calendar calendar = Calendar.getInstance();
        user.setMobile("3" + RandomStringUtils.random(10, String.valueOf(Long.parseLong(DateUtil.currentDateTimeStringTrim()) + calendar.getTimeInMillis())));
        accountDao.save(user);

        //保存志愿者信息
        volunteer.setUserId(user.getId());
        volunteer.setClient(user.getClient());

        this.volunteerService.saveVolunteer(volunteer);
    }

    @Override
    public void updatePassd(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String mobile = jsonObject.getString("mobile");
        String oldPasswd = jsonObject.getString("oldPasswd");
        String newPsswd = jsonObject.getString("newPsswd");
        if (StringUtils.isBlank(mobile))
            throw new ServiceRuntimeException("账号不能为空");
        if (StringUtils.isBlank(mobile))
            throw new ServiceRuntimeException("旧不能为空");
        if (StringUtils.isBlank(mobile))
            throw new ServiceRuntimeException("新不能为空");

        this.updatePsswd(mobile, oldPasswd, newPsswd);
    }

    @Override
    public void saveUser(User user) throws ServiceRuntimeException
    {
        //检查当前用户是否已存在
        User user1 = this.findByMobile(user.getMobile());
        if (null != user1)
            throw new ServiceRuntimeException("当前用户已存在");
        user1 = this.findByEmail(user.getMobile());
        if (null != user1)
            throw new ServiceRuntimeException("当前用户已存在");

        try
        {
            reg2BHPlatforpUser(user);
        } catch (Exception e)
        {
            e.printStackTrace();
            try
            {
                throw e;
            } catch (Exception e1)
            {
                e1.printStackTrace();
            }
        }

        user.setPassword(MD5Util.MD5(user.getPassword()));
        user.setRoles("user");
        user.setCreateTime(clock.getCurrentDate());

        accountDao.save(user);

        //保存志愿者信息
        Volunteer volunteer = new Volunteer();
        volunteer.setMemberCode(UUIDHexGenerator.generator());
        volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        volunteer.setMobile(user.getMobile());
        volunteer.setNickName(user.getNickName());
        volunteer.setRealName(user.getRealName());
        volunteer.setUserId(user.getId());
        volunteer.setHeadUrl(DKQConstant.HEAR_URL);
        volunteer.setTimes(0L);
        volunteer.setSex("男");
        this.volunteerService.saveVolunteer(volunteer);


    }

    @Override
    public User saveSimpleUser(User user) throws ServiceRuntimeException
    {
        //检查当前用户是否已存在
        User user1 = this.findByMobile(user.getMobile());
        if (null != user1)
            throw new ServiceRuntimeException("当前用户已存在");
        user1 = this.findByEmail(user.getMobile());
        if (null != user1)
            throw new ServiceRuntimeException("当前用户已存在");

        user.setPassword(MD5Util.MD5(user.getPassword()));
        user.setRoles("user");
        user.setCreateTime(clock.getCurrentDate());

        accountDao.save(user);
        return user;
    }

    private boolean checkVerifierCode(String mobile, String code)
    {
        boolean F = false;
        //绕过验证码注册
        if (code.equalsIgnoreCase("dakaqiCode"))
        {
            return true;
        }
        //检查验证码是否正确
        String sessionId = redisClientTemplate.get(mobile);
        if (StringUtils.isBlank(sessionId))
            return false;
        else
        {
            try
            {
                F = RongCloudSMS.verifyCode(sessionId, code);
                if(F == true)
                    redisClientTemplate.del(mobile);

            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return F;
    }

    @Override
    public void bundMobile(String param) throws ServiceRuntimeException
    {

        JSONObject jsonObject = JSON.parseObject(param);
        String memberCode = jsonObject.getString("memberCode");
        String mobile = jsonObject.getString("mobile");
        String code = jsonObject.getString("code");
        String passwd = jsonObject.getString("passwd");
        if (checkVerifierCode(mobile, code) == false)
        {
            String message = "手机验证码不正确";
            throw new ServiceRuntimeException(message);
        }

        //检查当前用户是否已存在
        Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
        if (null == volunteer)
            throw new ServiceRuntimeException("当前用户不存在");
        User user = findOne(volunteer.getUserId());
        if (null == user)
            throw new ServiceRuntimeException("当前用户不存在");
        User temp = findByMobile(mobile);
        if (null != temp)
            throw new ServiceRuntimeException("手机已被使用");

        user.setMobile(mobile);
        user.setPassword(MD5Util.MD5(passwd));
        accountDao.save(user);

        //保存志愿者信息
        volunteer.setMobile(user.getMobile());
        volunteer.setSex("男");
        this.volunteerService.saveVolunteer(volunteer);
        clearVeriferCode(user.getMobile());
    }

    @Override
    public void saveUser(String json, String client) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(json);
        String mobile = jsonObject.getString("mobile");
        String password = jsonObject.getString("password");
        String code = jsonObject.getString("code");
        String area = jsonObject.getString("area");
        double lng = jsonObject.getDoubleValue("lng");
        double lat = jsonObject.getDoubleValue("lat");
        int platform = jsonObject.getInteger("platform");

        if (StringUtils.isBlank(mobile))
        {
            String message = "账号不能为空";
            throw new ServiceRuntimeException(message);
        }
        if (StringUtils.isBlank(password))
        {
            String message = "密码不能为空";
            throw new ServiceRuntimeException(message);
        }
        User user = new User();
        user.setMobile(mobile);
        user.setPassword(password);
        user.setRealName("");
        user.setNickName(mobile);
        user.setRoles("user");
        user.setEmail(mobile + "@dakaqi.cn");
        user.setPlatform(platform);
        user.setArea(area);
        user.setLng(lng);
        user.setLat(lat);
        user.setClient(client);
        this.saveUser(user, code);
    }

    private void updatePsswd(String mobile, String oldPasswd, String newPasswd) throws ServiceRuntimeException
    {
        User user = findByMobile(mobile);
        if (null == user)
            throw new ServiceRuntimeException("用户不存在");

        if (!user.getPassword().toLowerCase().equals(MD5Util.MD5(oldPasswd).toLowerCase()))
            throw new ServiceRuntimeException("原密码不正确");

        if (!MD5Util.MD5(newPasswd).equals(MD5Util.MD5(oldPasswd)))
        {
            user.setPassword(MD5Util.MD5(newPasswd));
            accountDao.save(user);
        }
    }

    @Override
    public void updatePsswd(Long id, String oldPasswd, String newPasswd) throws ServiceRuntimeException
    {
        User user = getUser(id);
        if (null == user)
            throw new ServiceRuntimeException("当前用户不存在");

        if (!user.getPassword().toLowerCase().equals(MD5Util.MD5(oldPasswd).toLowerCase()))
            throw new ServiceRuntimeException("原密码不正确");

        if (!MD5Util.MD5(newPasswd).equals(MD5Util.MD5(oldPasswd)))
        {
            user.setPassword(MD5Util.MD5(newPasswd));
            accountDao.save(user);
        }
    }

    @Override
    public void updateUser(String json) throws ServiceRuntimeException
    {

    }

    public void updateUser(User user)
    {
        accountDao.save(user);
    }

    @Override
    public void deleteUser(Long id) throws ServiceRuntimeException
    {
        User user = getUser(id);
        if (null == user)
            throw new ServiceRuntimeException("当前用户不存在");
        user.setDelStatus(DKQConstant.DEL_YES);
        accountDao.save(user);
    }

    @Override
    public void lockUser(Long id, int lockedStatus) throws ServiceRuntimeException
    {
        User user = getUser(id);
        if (null == user)
            throw new ServiceRuntimeException("当前用户不存在");
        user.setLocked(lockedStatus);
        accountDao.save(user);
    }

    @Override
    public void setNewPasswd(String mobile, String passwd) throws ServiceRuntimeException
    {
        User user = findByMobile(mobile);
        user.setPassword(MD5Util.MD5(passwd));
        accountDao.save(user);
    }

    @Override
    public void setNewPasswd(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String mobile = jsonObject.getString("mobile");
        String passwd = jsonObject.getString("passwd");
        String code = jsonObject.getString("code");

        //检查验证码是否正确
        if (checkVerifierCode(mobile, code) == true)
        {
            this.setNewPasswd(mobile, passwd);
            clearVeriferCode(mobile);
        } else
        {
            String message = "手机验证码不正确";
            throw new ServiceRuntimeException(message);
        }
    }

    @Override
    public String sendVerifierCode(String mobile) throws ServiceRuntimeException
    {
        String sessionId = "";
        /*try
        {
            //发送手机验证码
            sessionId = get4Rand();
            String value = SendSMS.sendMsgFromTemplate(mobile.trim(), randCode);
            System.out.println(value);
            redisClientTemplate.set(mobile, randCode);
            redisClientTemplate.expire(mobile, 60 * 10);
        } catch (Exception e)
        {
            e.printStackTrace();
        }*/

        try
        {
            sessionId = RongCloudSMS.sendCode(mobile);
            redisClientTemplate.set(mobile, sessionId);
            redisClientTemplate.expire(mobile, 60 * 10);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return sessionId;
    }

    @Override
    public void updateMobile(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String oldMobile = jsonObject.getString("oldMobile");
        String password = jsonObject.getString("password");
        String newMobile = jsonObject.getString("newMobile");
        String code = jsonObject.getString("code");
        this.updateMobile(oldMobile, password, newMobile, code);
    }

    @Override
    public void updateMobile(String oldMobile, String password, String newMobile, String code) throws ServiceRuntimeException
    {
        //检查验证码是否正确
        if (checkVerifierCode(newMobile, code) == false)
        {
            String message = "手机验证码不正确";
            throw new ServiceRuntimeException(message);
        }

        //检查新的手机用户是否存在
        User temp = findByMobile(newMobile);
        if (null != temp)
            throw new ServiceRuntimeException("新的手机已存在");

        //检查旧的手机用户是否存在
        User user = findByMobile(oldMobile);
        if (null == user)
            throw new ServiceRuntimeException("旧的手机不存在");
        if (!user.getPassword().equalsIgnoreCase(MD5Util.MD5(password)))
        {
            throw new ServiceRuntimeException("密码与手机号匹配");
        }

        user.setMobile(newMobile);
        this.accountDao.save(user);
        volunteerService.updateMobile(oldMobile, newMobile);
    }

    @Override
    public void updateMobile(String oldMobile, String newMobile) throws ServiceRuntimeException
    {
        //检查新的手机用户是否存在
        User temp = findByMobile(newMobile);
        if (null != temp)
            throw new ServiceRuntimeException("新的手机已存在");

        //检查旧的手机用户是否存在
        User user = findByMobile(oldMobile);
        if (null == user)
            throw new ServiceRuntimeException("旧的手机不存在");

        user.setMobile(newMobile);
        this.accountDao.save(user);
        volunteerService.updateMobile(oldMobile, newMobile);
    }

    @Override
    public void updateMobile(String oldMobile, String newMobile, String code) throws ServiceRuntimeException
    {
        //检查验证码是否正确
        if (redisClientTemplate.get(newMobile.trim()) == null || !redisClientTemplate.get(newMobile).equals(code))
        {
            String message = "手机验证码不正确";
            throw new ServiceRuntimeException(message);
        }

        //检查新的手机用户是否存在
        User temp = findByMobile(newMobile);
        if (null != temp)
            throw new ServiceRuntimeException("新的手机已存在");

        //检查旧的手机用户是否存在
        User user = findByMobile(oldMobile);
        if (null == user)
            throw new ServiceRuntimeException("旧的手机不存在");

        user.setMobile(newMobile);
        this.accountDao.save(user);
        volunteerService.updateMobile(oldMobile, newMobile);
        clearVeriferCode(newMobile);
    }

    @Override
    public User tencent(String param, String client)
    {
        User user = null;
        JSONObject jsonObject = JSON.parseObject(param);
        String key = jsonObject.getString("appID");
        String token = jsonObject.getString("token");
        String openid = jsonObject.getString("openid");
        int platform = jsonObject.getIntValue("platform");
        String area = jsonObject.getString("area");
        double lng = jsonObject.getDoubleValue("lng");
        double lat = jsonObject.getDoubleValue("lat");
        String apiURL = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=" + key + "&access_token=" + token + "&openid=" + openid + "&format=json";
        String returnMessage = sendGet(apiURL);
        JSONObject qqJSON = JSON.parseObject(returnMessage);

        String head = qqJSON.getString("figureurl_2");    //用户头像图片
        String headm = qqJSON.getString("figureurl_1");    //用户头像图片
        String heads = qqJSON.getString("figureurl");    //用户头像图片
        String email = "qqc_" + openid + "@dakaqi.cn";
        user = this.findByEmail(email);
        if (null != user)
            return user;

        user = new User();
        user.setNickName(qqJSON.getString("nickname"));
        user.setEmail(email);
        user.setPlatform(platform);
        user.setLat(lat);
        user.setLng(lng);
        user.setArea(area);
        user.setClient(client);

        Volunteer volunteer = new Volunteer();
        volunteer.setMemberCode(UUIDHexGenerator.generator());
        volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        volunteer.setMobile(user.getMobile());
        volunteer.setNickName(user.getNickName());
        volunteer.setRealName(user.getRealName());
        volunteer.setSex("男");
        volunteer.setHeadUrl(head);
        volunteer.setTimes(0L);

        this.saveThirdPartyUser(user, volunteer);
        return user;
    }

    @Override
    public User signIn(String param, String client)
    {
        User user = null;
        Volunteer volunteer = new Volunteer();
        JSONObject jsonObject = JSON.parseObject(param);
        String openid = jsonObject.getString("openId");
        String token = jsonObject.getString("token");
        int platform = jsonObject.getIntValue("platform");

        UserOpenId userOpenId = userOpenIdDao.findByOpenIdAndType(openid, platform);
        if (userOpenId != null)
        {
            user = accountDao.findById(Integer.parseInt(userOpenId.getId() + ""));
            return user;
        } else
        {

            if (platform == 2)
            {
                tencent(param, client);
            } else if (platform == 3)
            {

                sina(param, client);

            } else if (platform == 4)
            {


                String urlParam = "access_token=" + token + "&openid=" + openid;
                String wechatUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" + urlParam;
                String returnMessage = sendGet(wechatUserInfoUrl);
                try
                {
                    JSONObject wechatInfo = JSON.parseObject(returnMessage);

                    String email = "wechat_" + openid + "@dakaqi.cn";
                    user = new User();
                    user.setEmail(email);
                    user.setPlatform(platform);
                    user.setRealName(wechatInfo.getString("nickName"));
                    user.setNickName(wechatInfo.getString("nickName"));

                    volunteer.setMemberCode(UUIDHexGenerator.generator());
                    volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
                    volunteer.setMobile(user.getMobile());
                    volunteer.setNickName(user.getNickName());
                    volunteer.setRealName(user.getRealName());
                    volunteer.setSex(wechatInfo.getIntValue("sex") == 1 ? "男" : "女");
                    volunteer.setProvince(wechatInfo.getString("province"));
                    volunteer.setCity(wechatInfo.getString("city"));
                    volunteer.setSex("男");
                    volunteer.setHeadUrl(wechatInfo.getString("headimgurl"));
                    volunteer.setTimes(0L);
                    //volunteer.setResidenceAddress(volunteer.getProvince()+"-" +volunteer.getCity());

                    this.saveThirdPartyUser(user, volunteer);

                } catch (Exception e)
                {
                    e.printStackTrace();
                }

            } else
            {
                return null;
            }
            if (user != null)
            {
                UserOpenId saveOpenId = new UserOpenId();
                saveOpenId.setMemberCode(volunteer.getMemberCode());
                saveOpenId.setCreateTime(new Timestamp(new Date().getTime()));
                saveOpenId.setEffectiveTime(0);//default 0   anytime
                saveOpenId.setOpenId(openid);
                saveOpenId.setType(platform);
                userOpenIdDao.save(saveOpenId);
            }
        }

        return user;
    }

    @Override
    public UserOpenId save(UserOpenId userOpenId)
    {
        return userOpenIdDao.save(userOpenId);
    }

    @Override
    public UserOpenId findOpenId(String memberCode, int type, String client)
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("memberCode", new SearchFilter("memberCode", SearchFilter.Operator.EQ, memberCode));
        filters.put("type", new SearchFilter("type", SearchFilter.Operator.EQ, type));
        Specification<UserOpenId> spec = DynamicSpecifications.bySearchFilter(filters.values(), UserOpenId.class);
        List<UserOpenId> list = this.userOpenIdDao.findAll(spec);
        if (null != list && list.size() > 0)
            return list.get(0);

        return null;
    }


    @Override
    public User sina(String param, String client)
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String appID = jsonObject.getString("appID");
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("token");
        int platform = jsonObject.getIntValue("platform");
        String area = jsonObject.getString("area");
        double lng = jsonObject.getDoubleValue("lng");
        double lat = jsonObject.getDoubleValue("lat");

        //获得微薄用户资料
        String apiURL = "https://api.weibo.com/2/users/show.json?access_token=" + token + "&uid=" + openid;
        String returnMessage = sendGet(apiURL);
        JSONObject sinaUser = JSON.parseObject(returnMessage);

        //第三方平台登录时，自动构造email
        String email = "sina_" + openid + "@dakaqi.cn";
        User user = findByEmail(email);
        if (null != user)
            return user;

        //User [id=5244677318, screenName=Iam彬哈哈, name=Iam彬哈哈, province=22, city=4, location=吉林 辽源, description=, url=, profileImageUrl=http://tva3.sinaimg.cn/default/images/default_avatar_male_50.gif, userDomain=, gender=m, followersCount=4, friendsCount=97, statusesCount=58, favouritesCount=1, createdAt=Tue Aug 12 12:55:40 CST 2014, following=false, verified=false, verifiedType=-1, allowAllActMsg=false, allowAllComment=true, followMe=false, avatarLarge=http://tva3.sinaimg.cn/default/images/default_avatar_male_180.gif, onlineStatus=0, status=Status [user=null, idstr=3885969311119066, createdAt=Fri Sep 11 19:25:44 CST 2015, id=3885969311119066, text=转发微博, source=Source [url=http://weibo.com/, relationShip=nofollow, name=微博 weibo.com], favorited=false, truncated=false, inReplyToStatusId=-1, inReplyToUserId=-1, inReplyToScreenName=, thumbnailPic=, bmiddlePic=, originalPic=, retweetedStatus=null, geo=null, latitude=-1.0, longitude=-1.0, repostsCount=0, commentsCount=0, mid=3885969311119066, annotations=, mlevel=0, visible=Visible [type=0, list_id=0]], biFollowersCount=2, remark=null, lang=zh-cn, verifiedReason=, weihao=, statusId=]


        user = new User();
        user.setNickName(sinaUser.getString("screen_name"));
        user.setRealName(sinaUser.getString("name"));
        user.setEmail(email);
        user.setPlatform(platform);
        user.setLat(lat);
        user.setLng(lng);
        user.setArea(area);
        user.setClient(client);

        Volunteer volunteer = new Volunteer();
        volunteer.setMemberCode(UUIDHexGenerator.generator());
        volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
        volunteer.setMobile(user.getMobile());
        volunteer.setNickName(user.getNickName());
        volunteer.setRealName(user.getRealName());
        volunteer.setSex("男");
        volunteer.setHeadUrl(sinaUser.getString("profile_image_url"));
        volunteer.setTimes(0L);
        this.saveThirdPartyUser(user, volunteer);


        return user;
    }

    @Override
    public User wechat(String param, String client) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String appID = jsonObject.getString("appID");
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("token");
        int platform = jsonObject.getIntValue("platform");
        String area = jsonObject.getString("area");
        double lng = jsonObject.getDoubleValue("lng");
        double lat = jsonObject.getDoubleValue("lat");

        String urlParam = "access_token=" + token + "&openid=" + openid;
        String wechatUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" + urlParam;
        String returnMessage = sendGet(wechatUserInfoUrl);
        try
        {
            JSONObject wechatInfo = JSON.parseObject(returnMessage);
            String email = "wechat_" + openid + "@dakaqi.cn";
            User user = findByEmail(email);
            if (null != user)
                return user;

            user = new User();
            user.setEmail(email);
            user.setPlatform(platform);
            user.setRealName(wechatInfo.getString("nickname"));
            user.setNickName(wechatInfo.getString("nickname"));
            user.setArea(area);
            user.setLat(lat);
            user.setLng(lng);
            user.setClient(client);

            Volunteer volunteer = new Volunteer();
            volunteer.setMemberCode(UUIDHexGenerator.generator());
            volunteer.setCrateTime(Clock.DEFAULT.getCurrentDate());
            volunteer.setMobile(user.getMobile());
            volunteer.setNickName(user.getNickName());
            volunteer.setRealName(user.getRealName());
            volunteer.setSex(wechatInfo.getIntValue("sex") == 1 ? "男" : "女");
            volunteer.setHeadUrl(wechatInfo.getString("headimgurl"));
            volunteer.setTimes(0L);
            this.saveThirdPartyUser(user, volunteer);
            return user;
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void regUser(Volunteer volunteer, String groupCode) throws ServiceRuntimeException
    {
        //注册一个新用户
        User user = new User();
        user.setMobile(volunteer.getMobile());
        user.setPassword(MD5Util.MD5(volunteer.getWeChat()));
        user.setPlatform(DKQConstant.USER_PLATFORM_WEB);
        user.setCreateTime(cn.dakaqi.utils.Clock.DEFAULT.getCurrentDate());
        user.setRealName(volunteer.getRealName());
        user.setNickName(volunteer.getNickName());
        user.setEmail(volunteer.getMobile() + "@dakaqi.cn");
        user.setRoles("user");
        this.accountDao.save(user);

        //注册一个志愿者
        volunteer.setUserId(user.getId());
        volunteer.setMemberCode(UUIDHexGenerator.generator());
        volunteer.setTimes(0L);
        volunteer.setCardType("CID");
        volunteer.setHeadUrl(DKQConstant.HEAR_URL);
        volunteer.setSex("男");
        this.volunteerService.saveVolunteer(volunteer);
        //将当前志愿者加当前社团
        GroupVolunteer groupVolunteer = new GroupVolunteer();
        groupVolunteer.setVolunteer(volunteer);
        Group group = this.groupService.findByGroupCode(groupCode);
        groupVolunteer.setGroup(group);
        groupVolunteer.setRole(DKQConstant.ROLES_VOLUNTEER);
        groupVolunteer.setStatus(DKQConstant.APPLY_STATUS_OK);
        groupVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
        groupVolunteer.setDelStatus(DKQConstant.DEL_NO);
        this.groupVolunteerService.save(groupVolunteer);
    }

    private static String get4Rand()
    {
        Random rand = new Random();
        int tmp = Math.abs(rand.nextInt());
        return String.valueOf(tmp % (9999 - 1000 + 1) + 1000);
    }

    private static String get6Rand()
    {
        Random rand = new Random();
        int tmp = Math.abs(rand.nextInt());
        return String.valueOf(tmp % (999999 - 100000 + 1) + 100000);
    }

    private void clearVeriferCode(String mobile)
    {
        redisClientTemplate.del(mobile);
    }

    public void setClock(Clock clock)
    {
        this.clock = clock;
    }

    public static String sendGet(String url)
    {
        String result = "";
        BufferedReader in = null;
        try
        {

            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            //for (String key : map.keySet()) {
            //    System.out.println(key + "--->" + map.get(key));
            //}
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
            {
                result += line;
            }
        } catch (Exception e)
        {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            } catch (Exception e2)
            {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
